<template>
	<el-form size="large" class="login-content-form">
		<el-form-item class="login-animation1">
			<el-input text placeholder="用户名 admin 或不输均为 common" v-model="state.ruleForm.loginName" clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2">
			<el-input
				:type="state.isShowPassword ? 'text' : 'password'"
				placeholder="密码：123456"
				v-model="state.ruleForm.loginPwd"
				autocomplete="off"
			>
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="state.isShowPassword = !state.isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" round @click="onSignIn" :loading="state.loading.signIn">
				<span>登 录</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts" name="loginAccount">
import { reactive, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Local, Session } from '/@/utils/storage';
import { NextLoading } from '/@/utils/loading';
import { loginApi } from './api';
import Watermark from '/@/utils/wartermark';
import { useThemeConfig } from '/@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { SM2 } from 'gm-crypto';



// 定义变量内容

// 引入 api 请求接口
const api = loginApi();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();
const state = reactive({
	isShowPassword: false,
	ruleForm: {
		loginName: 'admin',
		loginPwd: '123456',
	},
	submitForm: {
		loginName: '',
		loginPwd: '',
		keyId:""
	},
	loading: {
		signIn: false,
	},
});

// 时间获取
const currentTime = computed(() => {
	let hour: number = new Date().getHours();
	if (hour < 6) return '凌晨好';
	else if (hour < 9) return '早上好';
	else if (hour < 12) return '上午好';
	else if (hour < 14) return '中午好';
	else if (hour < 17) return '下午好';
	else if (hour < 19) return '傍晚好';
	else if (hour < 22) return '晚上好';
	else return '夜里好';
});
// 登录
const onSignIn = async () => {
	try {
		//开启登录按钮特效
		state.loading.signIn = true;
		//后台获取公钥信息
		const keyRes =  await api.getPublicKey();
		const keyId = keyRes.data.keyId;
		const publicKey = keyRes.data.publicKey;
		const cipherMode = {
			inputEncoding: 'utf8',
			outputEncoding: 'hex'
		}
		//SM2加密
		state.submitForm.loginName = SM2.encrypt(state.ruleForm.loginName, publicKey, cipherMode);
		state.submitForm.loginPwd = SM2.encrypt(state.ruleForm.loginPwd, publicKey, cipherMode);
		state.submitForm.keyId = keyId;
		//登录
		const loginRes =  await api.login(state.submitForm);
		// 存储 token 到浏览器缓存
		Session.set('token', loginRes.data.token);
		// 存储 roleName 到浏览器缓存
		Session.set('roleId', loginRes.data.roleId);
		Cookies.set('userName', loginRes.data.userName);

		// 从后台获取动态路由
		// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
		const isNoPower = await initBackEndControlRoutes();
		// 执行完 initBackEndControlRoutes，再执行 signInSuccess
		signInSuccess(isNoPower);
		
	} catch (error:any) {
		//关闭登录按钮特效
		state.loading.signIn = false;
		ElMessage.warning(error.message);
		Session.clear();
	}
	
};
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		//改变水印内容
		setWartermarkTextInput(state.ruleForm.loginName)
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 登录成功提示
		const signInText = '欢迎回来！';
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
	state.loading.signIn = false;
};
// 获取布局配置信息
const getThemeConfig = computed(() => {
	return themeConfig.value;
});
// 界面显示 --> 水印文案
const setWartermarkTextInput = (val: string) => {
	if(val === '') {
		if (getThemeConfig.value.isWartermark) Watermark.set(getThemeConfig.value.wartermarkText);
	} else {
		getThemeConfig.value.wartermarkText = val;
		if (getThemeConfig.value.isWartermark) Watermark.set(getThemeConfig.value.wartermarkText);
	}
	Local.remove('themeConfig');
	Local.set('themeConfig', themeConfig.value);
};

</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;
		&:hover {
			color: #909399;
		}
	}
	.login-content-code {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
}
</style>
